package cn.stylefeng.guns.modular.cb.service.impl;

import cn.stylefeng.guns.modular.cb.entity.CbWxInfo;
import cn.stylefeng.guns.modular.cb.service.CbWxUserService;
import cn.stylefeng.guns.modular.cb.util.AESForWeixinGetPhoneNumber;
import cn.stylefeng.guns.modular.cb.util.WeixinPhoneDecryptInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 微信服务类
 */
@Service
public class WxService {

    private static Logger logger = LoggerFactory.getLogger(WxService.class);

    @Value("${wx.appid}")
    private String appid;

    @Autowired
    private CbWxUserService cbWxUserService;

    /**
     * 解析电话号码
     * @param wxInfo
     * @return
     */
    public String getPhone(CbWxInfo wxInfo){
        String encryptedData = wxInfo.getEncryptedData();
        String iv = wxInfo.getIv();
        String openid = wxInfo.getOpenid();

        String sessionKey = cbWxUserService.findByOpenid(openid);
        AESForWeixinGetPhoneNumber aes=new AESForWeixinGetPhoneNumber(encryptedData,sessionKey,iv);
        WeixinPhoneDecryptInfo info=aes.decrypt();
        if (null==info){
            return "";
        }else {
            if (!info.getWeixinWaterMark().getAppid().equals(appid)){
                logger.info("解析微信电话号码失败，appid: {} 错误", appid);
                return "";
            }
        }
        return info.getPhoneNumber();
    }
}
